package com.greateffect.littlebud.lib.leaks;

import android.content.Context;
import android.os.Build;
import android.view.inputmethod.InputMethodManager;

import java.lang.reflect.Field;

/**
 * Created by ZengCS on 2019/6/12.
 * function：修复华为6.0系统出现mLastSrvView内存泄漏问题
 */
public class FixHuaWeiMemLeak {

    private static Field field;
    private static boolean hasField = true;

    /**
     * 检查是否是华为设备
     * @return
     */
    private static boolean isHuaweiDevice(){
        return "HUAWEI".equalsIgnoreCase(Build.BRAND);
    }

    public static void fixLeak(Context context) {
        //非华为设备不执行
        if(!isHuaweiDevice()) return;
        if (!hasField) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mLastSrvView"};
        for (String param : arr) {
            try {
                if (field == null) {
                    field = imm.getClass().getDeclaredField(param);
                }
                if (field == null) {
                    hasField = false;
                }
                if (field != null) {
                    field.setAccessible(true);
                    field.set(imm, null);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
}
